package com.ray.auth.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.ray.auth.common.CommonValue;
import com.ray.auth.system.service.DictTypeService;
import com.ray.auth.system.table.entity.DictType;
import com.ray.auth.system.table.entity.DictTypeExample;
import com.ray.auth.system.table.entity.DictTypeExample.Criteria;
import com.ray.auth.system.table.mapper.DictTypeMapper;
import com.xiaoleilu.hutool.util.StrUtil;
import com.zjhc.flyhong.common.datastructure.TreeNode;
import com.zjhc.flyhong.common.function.enums.DeleteEnum;
import com.zjhc.flyhong.common.function.exception.BussinessException;
import com.zjhc.flyhong.common.function.operator.LoginUser;
import com.zjhc.flyhong.common.function.operator.PageDto;
import com.zjhc.flyhong.common.function.validate.EntityValidate;
import com.zjhc.flyhong.common.function.validate.rule.FieldRule;
import com.zjhc.flyhong.common.function.validate.rule.RuleEnum;
import com.zjhc.flyhong.common.util.UUIDUtil;
import com.zjhc.flyhong.common.web.ErrorMsg;
import com.zjhc.flyhong.common.web.Result;
import com.zjhc.flyhong.common.web.ResultHelper;
import com.zjhc.flyhong.common.web.SuccessMsg;
import com.zjhc.flyhong.common.web.base.BaseService;
/**
 * <h1>系统权限应用  字典类型  服务实现</h1>
 * @创建人 ray
 * @创建时间 2017-06-10
 * @版本 1.0
 * @重要修改备注 
 * 
 */
@Service
public class DictTypeServiceImpl extends BaseService implements DictTypeService {
	/**日志对象**/
	private static Logger logger = Logger.getLogger(DictTypeServiceImpl.class);
	
	@Autowired
	private DictTypeMapper dictTypeMapper;
	/**************实现类  其他对象 引用  开始***********************/

	@Transactional
	public Result<Object> saveDictType(DictType entity, LoginUser loginUser) {
		//对象验证 
		/*****************验证开始************************/	
		FieldRule fieldRule = new FieldRule();
		fieldRule.addRule(RuleEnum.IS_NOT_NULL, String.class, "typeName","类型名称")
		.addRule(RuleEnum.IS_NOT_NULL, String.class, "dictTypeId", "字典类型");
		Result<Object> rs =	EntityValidate.validate(entity, fieldRule);
		if(!rs.codeSuccess())return rs;
		/******************验证结束*******************/
		entity.setTenantId(loginUser.getTenantId());
		entity.setIsDelete(DeleteEnum.USE.getValue());
		this.setUserForAdd(entity, loginUser);
		//执行成功数量	
		int exeCount = dictTypeMapper.insertSelective(entity);
		if(exeCount != 1)return ResultHelper.getError();
		return ResultHelper.getSuccess();
	}
	 /**
     * 通过父节点获取字典类型资源
     * @param id 父节点
     * @param loginUser 登录用户
     * @return
     */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public List<TreeNode> queryDictTypeListByParentId(String id, Integer level, LoginUser loginUser) {
		List<TreeNode> list = new ArrayList<TreeNode>();
		//为空时候 新增一个虚拟节点
		if(StrUtil.isBlank(id)){
			TreeNode node = new TreeNode(CommonValue.treeTopId, CommonValue.treeTopTypeName,1,false);
			list.add(node);
		}else{
			list.addAll(queryDictType(id,level,loginUser));
		}
		return list;
	}

	 /**
     * 查询当前id下的菜单
     * @param id
     * @param loginUser
     * @return
     */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	private List<TreeNode> queryDictType(String id, Integer level,LoginUser loginUser) {
		ArrayList<TreeNode> list = new ArrayList<TreeNode>();
		DictTypeExample example = new DictTypeExample();
		example.createCriteria().andParentDictTypeIdEqualTo(id)
		.andIsDeleteEqualTo(DeleteEnum.USE.getValue());
		example.setOrderByClause("INDEX_SORT ASC");
		List<DictType> typeList = dictTypeMapper.selectByExample(example);
		TreeNode node = null;
		for(DictType type : typeList){
			node = new TreeNode(type.getDictTypeId(), type.getTypeName(),level, false);
			node.setValue(type);
			list.add(node);
		}
		return list;
	}
	/**
	 * 查询所有从字典类型
	 * @param params 查询参数
	 * @param page 分页信息
	 * @param loginUser 登录用户
	 * @return
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public PageDto<DictType> queryDictTypeList(DictType params, PageDto<DictType> page, LoginUser loginUser) {
		DictTypeExample example = new DictTypeExample();
		Criteria criteria =  example.createCriteria();
		if(!loginUser.isSuperManager()){
			criteria.andTenantIdEqualTo(loginUser.getTenantId());
		}
		if(StrUtil.isNotBlank(params.getParentDictTypeId())){
			criteria.andParentDictTypeIdEqualTo(params.getParentDictTypeId());
		}
		criteria.andIsDeleteEqualTo(DeleteEnum.USE.getValue());
		this.setExamplePage(example, page);
		page.setTotal(dictTypeMapper.countByExample(example));
		page.setRecords(dictTypeMapper.selectByExample(example));
		return page;
	}
	 /**
     * 逻辑删除 字典类型数据
     * @param id 字典类型编号
     * @param loginUser 登录用户
     * @return
     */
	@Transactional
	public Result<Object> deleteDictType(String id, LoginUser loginUser) {
		Result<Object> result = null;
		result = new Result<Object>(0,SuccessMsg.OP_SUCCESS);
		DictTypeExample example = new DictTypeExample();
		example.createCriteria().andDictTypeIdEqualTo(id);
		DictType record = new DictType();
		record.setDictTypeId(UUIDUtil.getUUID());
		record.setIsDelete(DeleteEnum.DELETE.getValue());
		this.setUserForUpdate(record, loginUser);
		int opCount = dictTypeMapper.updateByExampleSelective(record, example);
		if(opCount != 1){
			logger.error("DictTypeServiceImpl=>deleteDictType is error");
			throw new BussinessException(-1, ErrorMsg.DELETE_ERROR);
		}
		return result;
	}
	 /**
     * 通过ID查询字典类型信息
     * @param id 类型编号
     * @param loginUser 登录用户
     * @return
     */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public DictType queryDictType(String id, LoginUser user) {
		return dictTypeMapper.selectByPrimaryKey(id);
	}
	/**
     * 修改字典类型信息
     * @param record 字典类型对象
     * @param user 登录用户
     * @return
     */
	@Transactional
	public Result<Object> updateDictType(DictType record, LoginUser loginUser) {
		Result<Object> result = null;
		result = new Result<Object>(0,SuccessMsg.OP_SUCCESS);
		this.setUserForUpdate(record, loginUser);
		int opCount = dictTypeMapper.updateByPrimaryKeySelective(record);
		if(opCount != 1){
			logger.error("DictTypeServiceImpl=>DictTypeUpdate is error");
			throw new BussinessException(-1, ErrorMsg.UPDATE_ERROR);
		}
		return result;
	}
	/**
     * 通过父节点id获取父节点信息 提供符节点ID 0 返回虚拟节点
     * @param patentDictTypeId
     * @param user
     * @return
     */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public DictType queryParentDictType(String patentTypeId, LoginUser user) {
		if(StrUtil.equals(patentTypeId, CommonValue.treeTopId)){
			DictType dictType = new DictType();
			dictType.setDictTypeId(CommonValue.treeTopId);
			dictType.setTypeName(CommonValue.treeTopTypeName);
			return dictType;
		}else{
			return queryDictType(patentTypeId, user);
		}
	}
	

}
